<template>
	<view class="my-container">
		<!-- 用户未登录 -->
		<block v-if="!openid">
			<u-icon class="u-icon" size="100" color="#36c956" name="weixin-circle-fill" @click="getUserInfo">
			</u-icon>
		</block>
		<!-- 已登录 -->
		<block v-else>
			<image class="avatar avatar-img" :src="userInfo.avatarUrl" mode="scaleToFill" />
			<view class="login-desc">{{ userInfo.nickName }}</view>
			<button class="login-btn" type="default" @click="onLogoutClick">
				退出登录
			</button>
		</block>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex';
	export default {
		name: 'my-login',
		data() {
			return {
				code: '',
			};
		},
		computed: {},
		methods: {
			onLogoutClick() {
				uni.showModal({
					title: '提示',
					content: '退出登录将无法同步数据哦~',
					success: ({
						confirm,
						cancel
					}) => {
						if (confirm) {
							this.logout();
						}
					},
				});
			},

			/**
			 *
			 * 获取用户信息
			 */
			getUserInfo() {
				// 展示加载框
				uni.showLoading({
					title: '加载中',
				});
				uni.getUserProfile({
					desc: '登录后可同步数据',
					success: async (obj) => {
						// 调用 action ，请求登录接口
						uni.login({
							provider: 'weixin',
							success: async (res) => {
								this.code = res.code;
								// console.log('登录获取code', res);
								if (res.errMsg == 'login:ok') {
									res.appid = "wxe828ff4caec0a248";
									this.$u.api.wxLogin(res).then(result => {
										if (result.code == '200') {
											setTimeout(() => {
												uni.reLaunch({
													url: '/pages/sys/msg/index'
												});
											}, 500);
										} else if (result
											.code == '401') {
											uni.reLaunch({
												url: '/pages/sys/login/index'
											});
										} else {
											this.$u.toast(result.message);
										}
									});
								}
							},
						});
					},
					fail: () => {
						uni.showToast({
							title: '授权已取消',
							icon: 'error',
							mask: true,
						});
					},
					complete: () => {
						// 隐藏loading
						uni.hideLoading();
					},
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.my-container {
		display: flex;
		flex-direction: column;
		align-items: center;

		.avatar-img {
			width: 78px;
			height: 78px;
		}

		.login-desc {
			color: #999;
			font-size: 14px;
			margin-top: 16px;
		}


	}
</style>
